import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms

# 确保你的计算机上已经安装了NVIDIA驱动和CUDA工具包，并且PyTorch版本与CUDA版本兼容
# 检查是否有可用的GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f'Using device: {device}')

# 数据预处理
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])

# 加载MNIST数据集
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)

train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=1000, shuffle=False)


# 定义简单的神经网络模型
class SimpleNN(nn.Module):
    def __init__(self):
        super(SimpleNN, self).__init__()
        self.flatten = nn.Flatten()
        self.fc1 = nn.Linear(28 * 28, 128)
        self.relu = nn.ReLU()
        self.dropout = nn.Dropout(0.2)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = self.flatten(x)
        x = self.fc1(x)
        x = self.relu(x)
        x = self.dropout(x)
        x = self.fc2(x)
        return x


# 训练模型（如果需要）
def train_model():
    model = SimpleNN().to(device)  # 将模型移动到设备上
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=0.001)

    for epoch in range(5):  # 训练5个epoch
        model.train()
        running_loss = 0.0
        for images, labels in train_loader:
            images, labels = images.to(device), labels.to(device)  # 将数据移动到设备上
            optimizer.zero_grad()
            outputs = model(images)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()
            running_loss += loss.item()
        print(f'Epoch [{epoch + 1}/5], Loss: {running_loss / len(train_loader)}')

    # 保存模型
    torch.save(model.state_dict(), 'mnist_simplenn.pth')
    print('Model saved to mnist_simplenn.pth')
    return model


# 加载模型
def load_model():
    model = SimpleNN().to(device)  # 创建模型实例并移动到设备上
    model.load_state_dict(torch.load('mnist_simplenn.pth'))  # 加载状态字典
    model.eval()  # 设置模型为评估模式
    return model


# 评估模型
def evaluate_model(model):
    correct = 0
    total = 0
    with torch.no_grad():
        for images, labels in test_loader:
            images, labels = images.to(device), labels.to(device)  # 将数据移动到设备上
            outputs = model(images)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    print(f'Accuracy of the network on the 10000 test images: {100 * correct / total}%')


# 主程序入口
if __name__ == '__main__':
    # 如果需要训练模型，请取消注释下面的行
    # model = train_model()

    # 加载已保存的模型
    model = load_model()

    # 评估模型
    evaluate_model(model)
